package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/5/27 11:37
 * @Version 1.0
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //  监听延迟消息：
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancel(Long orderId, Message message , Channel channel){
        //  保存订单的时候，orderInfo,paymentInfo,aliPay;  关闭的流程 有orderInfo, paymentInfo, aliPay.
        //  为什么不能一起关闭，closed。 还一个一个的判断{防止订单在过期的一瞬间用户完成付款}
        try {
            //  判断
            if (null != orderId){
                //  根据订单Id 获取到订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                //  利用业务字段防止消息重发消费.
                if (null != orderInfo && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  判断是否有paymentInfo
                    PaymentInfo paymentInfo = this.paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //  判断
                    if (null != paymentInfo && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //  查看是否有交易记录。
                        Boolean result = this.paymentFeignClient.checkPayment(orderId);
                        if (result){
                            //  用户用户扫码了！ 调用一个关闭方法
                            Boolean isSuccess = this.paymentFeignClient.closePay(orderId);
                            if (isSuccess){
                                //  说明关闭成功. 还需要关闭 orderInfo,paymentInfo;
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  说明关闭失败，用户在即将到期关闭的时候，完成了支付.
                            }

                        } else {
                            //    说明没有扫码！关闭两个orderInfo , paymentInfo;
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {
                        //  只需要关闭orderInfo;
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认：
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 监听关闭订单消息
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_CLOSED,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER_CLOSED),
            key = {MqConst.ROUTING_ORDER_CLOSED}
    ))
    public void orderClosed(Long orderId, Message message , Channel channel){
        try {
            //  判断
            if (null != orderId){
                //  利用业务字段防止重复消费
                OrderInfo orderInfo = orderService.getById(orderId);
                if (null != orderId && !"CLOSED".equals(orderInfo.getOrderStatus())){
                    //  调用服务层方法。
                    this.orderService.updateOrderStatus(orderId, ProcessStatus.CLOSED);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 监听支付成功消息，修改订单状态.
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId, Message message , Channel channel){
        try {
            //  判断
            if (null != orderId){
                //  利用业务字段防止重复消费
                OrderInfo orderInfo = orderService.getById(orderId);
                if (null != orderId && !"PAID".equals(orderInfo.getOrderStatus())){
                    //  调用服务层方法。
                    this.orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                    //  发送消息给库存系统
                    this.orderService.sendMsgToWare(orderId);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void wareOrder(String orderMsg, Message message , Channel channel){
        try {
            //  判断
            if (!StringUtils.isEmpty(orderMsg)){
                //  将Json 字符串转换为Java 对象
                Map map = JSON.parseObject(orderMsg, Map.class);
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  判断 减库存结果 status

                if ("DEDUCTED".equals(status)){
                    //  调用服务层方法。
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);
                } else {
                    //  减库存异常.
                    this.orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.STOCK_EXCEPTION);
                    //  记录当前哪个orderId,减库存失败。通知人工取补货. 如果补发成功，则根据这个订单Id 修改订单状态. 保证数据最终一致性.
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
